<template>
  <div class="content">
    <van-nav-bar :title="id && id != '' ? '修改商品' : '添加商品'" left-arrow  @click-left="toGoodsManager" fixed placeholder >
        <template #left>
            <img src="../../../assets/back.png" alt="" class="back">
        </template>
    </van-nav-bar>
    <div class="goods-info">
        <div class="title title-line">商品信息</div>
        <div class="item">
            <div class="label">*商品分类</div>
            <div class="input-content">
                <van-field v-model="category" placeholder="设置商品分类" class="input" readonly @click="showPicker = true">
                    <template #right-icon>
                        <van-icon name="arrow" />
                    </template>
                </van-field>
                <div class="end"></div>
            </div>
        </div>
        <div class="item">
            <div class="label">*商品名称</div>
            <div class="input-content">
                <van-field v-model="title" placeholder="设置商品名称" class="input"> </van-field>
                <div class="end"></div>
            </div>
        </div>
        <div class="item">
            <div class="label">*商品价格（元）</div>
            <div class="input-content">
                <van-field v-model="price" placeholder="设置商品售价" class="input"> </van-field>
                <div class="end">元</div>
            </div>
        </div>
        <div class="item">
            <div class="label">*商品库存（个）</div>
            <div class="input-content">
                <van-field v-model="stock" placeholder="设置商品库存数量" class="input"> </van-field>
                <div class="end">个</div>
            </div>
        </div>
        <div class="item">
            <div class="label">*分享者分润（%）</div>
            <div class="input-content">
                <van-field v-model="share" placeholder="设置商品分润" class="input"> </van-field>
                <div class="end">%</div>
            </div>
        </div>
        <div class="item">
            <div class="label">*商品详情</div>
            <van-field v-model="content" type="textarea" placeholder="这里是商品详情" class="input"/>
        </div>
    </div>
    <div class="goods-info">
        <div class="title">商品缩略图</div>
        <div class="tips">上传图片大小不能超过4M，单个商品可添加1张图片，点击图片查看大图</div>
        <van-uploader class="upload" v-model="goodsImg" max-count="1"   :after-read="goodsImgAfterRead" :delete="goodsImgDeleteImg" />
    </div>
    <div class="goods-info">
        <div class="title">商品轮播图</div>
        <div class="tips">上传图片大小不能超过4M，单个商品可添加9张图片，点击图片查看大图</div>
        <van-uploader class="upload" multiple  v-model="swiperImgs" max-count="9" :after-read="swiperImgsAfterRead" :delete="swiperImgsDeleteImg" />
    </div>
    <div class="bottom">
        <van-button class="btn" @click="submitGoods">{{id && id != '' ? '确认修改商品' : '确认添加商品'}}</van-button>
    </div>
    <van-popup v-model="showPicker" round position="bottom">
        <van-picker
            show-toolbar
            :columns="categoryList"
            @cancel="showPicker = false"
            @confirm="onConfirm"
            value-key="name"
        />
    </van-popup>
  </div>
</template>

<script>
import { getCategoryByShopId,SupplierAdd,SupplierEdit,postImages2,goodsDetailByShopGoodsList } from "@/api/api";
import { Dialog } from 'vant';
export default {

    data(){
        return {
            shop_id:1,
            id:'',
            category:'',
            categoryId:'',
            title:'',
            price:'',
            share:'',
            stock: '',
            content: '',
            goodsImg: [],
            image:'',
            swiperImgs:[],
            images:[],
            categoryList:[],
            showPicker:false,
        }
    },
    mounted(){
        if(this.$route.query.goodsId){
            this.id = this.$route.query.goodsId
            this.goodsDetailByShopGoodsList(this.$route.query.goodsId)
        }
        this.shopcategory()
    },
    methods:{
        shopcategory(){
            getCategoryByShopId({shop_id:this.shop_id}).then(res=>{
                this.categoryList = res.data.data
            })
        },
        goodsDetailByShopGoodsList(goodsId){
            goodsDetailByShopGoodsList({shop_id:this.shop_id,id:goodsId}).then(res=>{
                let {id,image,images,price,title,category,category_id,share,description,stock} = res.data.data
                this.id = id
                this.image = image
                this.goodsImg = [{url:image, isImage: true}]
                this.images = images ? images.split(',') : ''
                this.swiperImgs = this.images.map(i=>{return {url:i, isImage: true}})
                this.price = price
                this.title = title
                this.category = category.name
                this.categoryId = category_id
                this.share = share
                this.content = description
                this.stock = stock
            })
        },
        toGoodsManager(){
            this.$router.push("/goodsManager");
        },
        onConfirm(item){
            this.category = item.name
            this.categoryId = item.id
            this.showPicker = false
        },
        async goodsImgAfterRead (file) {
            this.image = await this.uploadImg(file.file)
        },
        //删除方法
        goodsImgDeleteImg () {
            this.goodsImg = []
            this.image = ''
        },
        async swiperImgsAfterRead (file) {
            if (file instanceof Array && file.length) {
                for(let i = 0;i<file.length;i++){
                    let item = file[i]
                    let imgUrl = await this.uploadImg(item.file)
                    this.images.push(imgUrl)
                }
            } else {
                let imgUrl = await this.uploadImg(file.file)
                this.images.push(imgUrl)
            }
        },
        //删除方法
        swiperImgsDeleteImg (file) {
            for (let i = 0, len = this.swiperImgs.length; i < len; i++) {
                if (file.file.name === this.swiperImgs[i].name && file.file.size === this.swiperImgs[i].size) {
                    this.swiperImgs.splice(i, 1)
                    this.images.splice(i, 1)
                    break
                }
            }
        },
        async uploadImg(file){
            var fd = new FormData();
            fd.append("file", file);
            let res = await postImages2(fd)
            return res.data.data.fullurl
        },
        submitGoods(){
            let params = {
                shop_id:this.shop_id,
                share:this.share,
                price:this.price,
                category_id:this.categoryId,
                title:this.title,
                stock:this.stock,
                content:this.content,
                image:this.image,
                images:this.images.join(',')
            }
            if(this.id && this.id != ''){
                SupplierEdit({id:this.id,...params}).then(res=>{
                    console.log(res);
                    if(res.data.code == 1){
                        Dialog.alert({
                            title: res.data.msg,
                            confirmButtonText:'我知道了'
                        }).then(() => {
                            this.toGoodsManager()
                        });
                    }else {
                        Dialog.alert({
                            title: res.data.msg,
                            confirmButtonText:'我知道了'
                        }).then(() => {
                        });
                    }
                })
            }else {
                SupplierAdd(params).then(res=>{
                    console.log(res);
                    if(res.data.code == 1){
                        this.toGoodsManager()
                    }else {
                        Dialog.alert({
                            title: res.data.msg,
                            confirmButtonText:'我知道了'
                        }).then(() => {
                        });
                    }
                })
            }
        }
    }
}
</script>

<style scoped>
/deep/.van-uploader__upload{
  order:-1;
}
div {
    box-sizing: border-box;
}
.content {
    background-color: #F8F8F8;
    padding-bottom: 80px;
}
.back {
    height: 22px;
}

.goods-info {
    margin-top: 10px;
    background-color: #fff;
    padding: 10px 20px 20px;
}
.goods-info .title {
    line-height: 50px;
    font-size: 18px;
    font-weight: 700;
}
.goods-info .title-line {
    border-bottom: 1px solid #eee;
}
.item .label {
    line-height: 40px;
    margin-top: 5px;
    color: #949494;
}
.input-content {
    display: flex;
    align-items: center;
}
.input {
    background-color: #f8f8f8;
    border-radius: 5px;
}
.end {
    width: 25px;
    height: 100%;
    text-align: center;
}

.tips {
    color: #949494;
    font-size: 12px;
}
.upload {
    margin-top: 10px;
}


.bottom {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100vw;
    height: 70px;
    background-color: #fff;
    display: flex;
    justify-content: center;
    padding: 10px;
}
.bottom .btn {
    width: 100%;
    height: 50px;
    line-height: 50px;
    border-radius: 25px;
    color: #fff;
    background-color: #FF3F4F;
    /* background-image: linear-gradient( to right , #FF3F4F , #FF3F4F); */
    font-size: 18px;
}
</style>